import { Button, Checkbox, Input, Message, Modal } from "@arco-design/web-react";
import { useContext, useState } from "react";
import { ChatContext } from "..";
import { IconClose, IconSearch } from "@arco-design/web-react/icon";
import { useDispatch, useSelector } from "react-redux";
import { LeoAvatar } from "../../../components/leo_Avatar";
import { addConversation, fetchConversationList } from "../../../store/features/conversation";
import { ContactsModelState, ConversationType } from "../../../domain/im/entity";
import { openMessage } from "../../../store/features/message";
import http from "../../../http";
import { fetchGroupMemberInfo } from "../../../store/features/group_member";

export const ContactsModel = () => {

    const { visibleGroup, setVisibleGroup, contactsModelState,members } = useContext(ChatContext);

    const { list, current } = useSelector((state: any) => state.conversation.value);

    const users = useSelector((state: any) => state.friend.value.users);

    const [selectUserId, setSelectUserId] = useState<any>([]);


    


    const removeUsers = async () => {
        const ids = selectUserId.map((item: any) => item.userId).join(',');
        const response: any = await http.get(`/group/remove?ids=${ids}&targetId=${list[current].targetId}`);
        if (response.code == 200) {
            setVisibleGroup(false);
            setSelectUserId([])
            dispatch(fetchGroupMemberInfo(list[current].targetId))
            const fetchMessage = async () => {
                const respones = await http.get("/message/list?targetId=" + list[current].targetId)
                dispatch(openMessage({ messages: respones.data, targetId: list[current].targetId }));
                console.log("请求完成")
            }
            fetchMessage();
        } else {
            Message.error(response.msg);

        }

    }

    const invitationUser = async () => {
        const ids = selectUserId.map((item: any) => item.userId).join(',');
        const response: any = await http.get(`/group/invitation?ids=${ids}&targetId=${list[current].targetId}`);
        if (response.code == 200) {
            setVisibleGroup(false);
            setSelectUserId([])
            dispatch(fetchGroupMemberInfo(list[current].targetId))
            const fetchMessage = async () => {
                const respones = await http.get("/message/list?targetId=" + list[current].targetId)
                dispatch(openMessage({ messages: respones.data, targetId: list[current].targetId }));
                console.log("请求完成")
            }
            fetchMessage();
        } else {
            Message.error(response.msg);

        }

    }

    const createGroup = async () => {
        const ids = selectUserId.map((item: any) => item.userId).join(',');
        const response = await http.get("/group/create?ids=" + ids);
        setVisibleGroup(false);
        setSelectUserId([])
        Message.success("创建成功");
        dispatch(fetchConversationList(list[current].targetId))
        const fetchMessage = async () => {
            const respones = await http.get("/message/list?targetId=" + response.data.groupId)
            dispatch(openMessage({ messages: respones.data, targetId: response.data.groupId }));
        }
        fetchMessage();
    }

    const dispatch = useDispatch();


    const elementItem = (item: any, index: any) => (<div className="mb-3" key={item.userId + 'index-2'}>
        <Checkbox className='mr-3' checked={
            selectUserId.findIndex((item1: any) => (item1.userId) == item.userId) == -1 ? false : true
        } onChange={(value) => {
            if (value) {
                setSelectUserId((prevState: any) => [...prevState, item]);
            } else {
                setSelectUserId((prevState: any) => [...prevState].filter((item1) => (item1.userId) !== item.userId));
            }
        }} />
        <LeoAvatar userPortrait={item.userPortrait} userName={item.nickName}></LeoAvatar>
        <span className="ml-3 text-[16px]">{item.userName}</span>
    </div>);

    return <Modal
        style={{ top: '-3%' }}
        className="shadow-2xl w-[650px] h-[400px] border border-gray-100 overflow-hidden rounded-xl"
        visible={visibleGroup}
        onOk={() => setVisibleGroup(false)}
        onCancel={() => {
            setSelectUserId([])
            setVisibleGroup(false);
        }}
        autoFocus={false}
        focusLock={false}
        footer={null}
        title={null}
        closeIcon={null}
    >
        <div className="flex flex-row h-[400px]">

            <div className="w-[300px] bg-gray-50 border h-full border-r-gray-300 p-5">
                <Input
                    maxLength={11}
                    prefix={<IconSearch />}
                    placeholder='搜索'
                    className='mb-6'
                />

                <div className="h-[335px] w-ful overflow-scroll">
                    {
                        (contactsModelState == ContactsModelState.create || contactsModelState == ContactsModelState.invitation ) && users && users.map((item: any, index: any) => elementItem(item,index))
                    }
                    {
                        (contactsModelState == ContactsModelState.remove ) && members && members.map((item: any, index: any) => elementItem(item,index))
                    }
                </div>

            </div>

            <div>
                <div className="w-[350px] bg-white flex flex-row justify-between p-3">
                    <span className="text-[16px] font-bold">

                        {
                            contactsModelState == ContactsModelState.create && '发起群聊'
                        }

                        {
                            contactsModelState == ContactsModelState.invitation && '邀请用户'
                        }
                        {
                            contactsModelState == ContactsModelState.remove && '移除群聊'
                        }
                    </span>
                    <span className="flex-1 text-right text-[12px] text-gray-400">
                        {selectUserId.length == 0 ? '未选择联系人' : '已选择 ' + selectUserId.length + ' 个联系人'}
                    </span>
                </div>
                <div>
                    <div className=" grid grid-cols-4 p-4 h-[270px] overflow-scroll">
                        {
                            selectUserId.map((item: any) =>
                                <div className="flex flex-col items-center justify-center relative mb-2 h-[70px]">
                                    <LeoAvatar userPortrait={item.userPortrait} userName={item.nickName}></LeoAvatar>
                                    <span className="mt-1">{item.userName}</span>

                                    <div onClick={() => {
                                        setSelectUserId((prevState: any) => [...prevState].filter((item1) => (item1.userId) !== item.userId));
                                    }} className="w-[15px] h-[15px] rounded-full bg-gray-400 absolute right-[10px] top-[-8px] text-center text-white  text-[10px]">
                                        <IconClose className="text-white font-bold text-[12px]"></IconClose>
                                    </div>

                                </div>)
                        }
                    </div>

                    <div className=" space-x-10 text-center mt-7">
                        <Button className="w-[100px] rounded-lg" onClick={() => {
                            setVisibleGroup(false);
                            setSelectUserId([])
                        }}>取消</Button>
                        {
                            contactsModelState == ContactsModelState.create && <Button onClick={() => createGroup()} className="w-[100px] rounded-lg">创建</Button>
                        }
                        {
                            contactsModelState == ContactsModelState.invitation && <Button onClick={() => invitationUser()} className="w-[100px] rounded-lg">邀请</Button>
                        }
                         {
                            contactsModelState == ContactsModelState.remove && <Button onClick={() => removeUsers()} className="w-[100px] rounded-lg">移除</Button>
                        }
                    </div>
                </div>
            </div>
        </div>

    </Modal>;
}